package com.ellricky.baselib.adapter;

import android.content.Context;
import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.andr.common.util.ScreenUtil;

public class CommonGridItemDecoration extends RecyclerView.ItemDecoration {


    private Context mContext;
    private int spacing;
    private int spanCount;
    private boolean includeEdge;

    public CommonGridItemDecoration(Context context, int spanCount, int space) {
        this(context, spanCount, space, true);
    }

    public CommonGridItemDecoration(Context context, int spanCount, int spacing, boolean includeEdge) {
        this.mContext = context;
        this.spanCount = spanCount;
        this.spacing = (int) ScreenUtil.dp2px(context, spacing);
        this.includeEdge = includeEdge;
    }


    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

//        int pos = parent.getChildAdapterPosition(view);
//        int column = (pos) % totalColumn + 1;// 计算这个child 处于第几列
//
//        outRect.top = 0;
//        outRect.bottom = space;
//        //注意这里一定要先乘 后除  先除数因为小于1然后强转int后会为0
//        //左侧为(当前条目数-1)/总条目数*divider宽度
//        outRect.left = (column - 1) * space / totalColumn;
//        //右侧为(总条目数-当前条目数)/总条目数*divider宽度
//        outRect.right = (totalColumn - column) * space / totalColumn;

        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // item top
            }
        }

    }
}

